const HtmlWebpackPlugin = require('html-webpack-plugin');
const pluginName = 'WeCodeCheckDoneHooksPlugin';
class WeCodeCheckDoneHooksPlugin {

  constructor(options = { message: null }) {
    this.options = options;
  }

  apply(compiler) {
    compiler.hooks.done.tap(pluginName, (stats) => {
      // 报错时，需通知IDE插件，处理，避免IDE一直处理监听状态，而无法处理其他任务。
      if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1) {
        error('Build fail.');
        const { message } = this.options;
        let requestMessage = null;
        try {
          requestMessage = JSON.parse(message);
        } catch (error) {
          log(error);
        }
        if (!requestMessage) {
          log('message arg is null.');
          return;
        }
        if (requestMessage && process && process.send) {
          const processMessage = {
            status: 'error',
            request: requestMessage, // 同一进程需要回相同数据给IDE，便于IDE识别进程类别如start或者build
            message: {
              tip: 'Build fail.',
              details: stats.compilation.errors.join(',')
            }
          };
          process.send(processMessage);
        }
      }
    })
    compiler.hooks.compilation.tap(pluginName, compilation => {
      HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
        pluginName,
        (htmlPluginData, cb) => {
          const {
            head = { links: [] },
            body = { scripts: [] }
          } = this.options; // 便于后续模板优化
          head.links.reverse().forEach(function(value) {
            htmlPluginData.head = [
              {
                "tagName": "link",
                "closeTag": true,
                "attributes": { "rel": "stylesheet", "href": value }
              }
            ].concat(htmlPluginData.head);
          });

          body.scripts.reverse().forEach(function(value) {
            htmlPluginData.body = [
              {
                "tagName": "script",
                "closeTag": true,
                "attributes": { "type": "text/javascript", "src": value }
              }
            ].concat(htmlPluginData.body);
          });
          return cb(null, htmlPluginData)
        }
      )
    })
  }
}
module.exports = WeCodeCheckDoneHooksPlugin;
